require(['jgGrid', 'bootstrap', 'underscore','cookie'], function () {
    var webRoot = G_WEB_ROOT;
    var grid_selector = "#productGrid";
    var pager_selector = "#productGridPager";
    
    var urls = {
    	findProductGrid : webRoot + "/sys/findProductGrid?brandId="+$("#brandId").val(),
    	deleteProductByIds : webRoot + '/sys/deleteProductByIds'
    };
    
    var selectClassifyId= '';
    
    var gridObj = {
    	searchTxt : null,
    	gridId : grid_selector,
		gridOpt : {
			 url: urls.findProductGrid,
		        datatype: 'json',
		        mtype: 'POST',
		        autowidth: true,
		        height: 630,
		        colNames: ['id', '名称', '售价','首期','月供', '是否发布', '是否热门','排序', '创建时间', '操作'],
		        colModel: [
		            {name: 'id', hidedlg: true, hidden: true, width: 60},
		            {name: 'name', sortable: false, editable: true, width: 200, align: 'center'},
		            {name: 'price', sortable: false, editable: true, width: 60, align: 'center'},
		            {name: 'downPayment', sortable: false, editable: true, width: 60, align: 'center'},
		            {name: 'monthlyPayment', sortable: false, editable: true, width: 60, align: 'center'},
		            {name: 'hasPublic',width: 100, sortable: false,editable: true,editoptions: {size: "20", maxlength: "30"},editrules: {required: true},formatter:function(v,o,r){
	                	return r.hasPublic==1?"是":"否";
                    } },
		            {name: 'hot',width: 100, sortable: false,editable: true,editoptions: {size: "20", maxlength: "30"},editrules: {required: true} ,formatter:function(v,o,r){
	                	return r.hot==1?"是":"否";
                    }},
		            {name: 'showIndex',width:120,sortable:false,editable:true,align:'center',editoptions:{size:"20",maxlength:"5"},editrules:{required:true}},
		            {name:'createTime',width:100,sortable:false,align:'center',editable:false,sorttype:"date",editrules:{required:true}},
		            {name:'myac',width:200,fixed:true,sortable:false,align:'center',resize:false,search:false,title:false}
		        ],
		        viewrecords: true,
		        pager: pager_selector,
		        altRows: true,
		        rowHeight: 36,
		        styleUI: 'Bootstrap',
		        multiselect: true,
		        multiboxonly: true,
		        loadComplete: function (xhr) {
		            var rows = xhr.rows;
		            var ids = $(gridObj.gridId).jqGrid('getDataIDs');
		            for (var i = 0; i < ids.length; i++) {
		                var col = ids[i];
		                var html = '<a href="javascript:void(0)" data-index="' + i + '" class="go2EditView" style="padding-right:5px;">产品编辑</a>' ;
		                $(gridObj.gridId).jqGrid('setRowData', col, {myac: html});
		            }
		            $('.go2EditView').unbind().bind('click', function (e) {
		                var _this = $(this);
		                var idx = _this.attr('data-index');
		                var rowObj = rows[idx];
		                console.log(rowObj);
		                window.location.href = 
		                	webRoot + '/sys/editView?productId=' + rowObj.id +'&brandId='+parseInt($("#brandId").val())
		                			+'&name='+rowObj.name +'&price='+rowObj.price 
		                			+'&downPayment='+rowObj.downPayment +'&monthlyPayment='+rowObj.monthlyPayment;
		                
		            });
		        },
		        onSelectRow:function(id){
		        }
		},
        init: function (_brandId, _searchTxt) {
            var self = this;
//            if (_.isNull(_brandId, self.searchTxt)) {
//                $(self.gridId).jqGrid(self.gridOpt);
//            }
//            if (_brandId, _searchTxt != self.searchTxt) {
//                self.searchTxt = _searchTxt;
//                self.initGrid(_brandId, _searchTxt);
//            }
            $(self.gridId).jqGrid(self.gridOpt);
//            console.log(_brandId, _searchTxt);
//            self.initGrid(_brandId, _searchTxt);
        },
        initGrid: function (_brandId,_searchTxt) {
        	console.log(_brandId,_searchTxt);
            var self = this;
            $(self.gridId).clearGridData().
            	setGridParam({postData: {'brandId':_brandId,'searchTxt': _searchTxt}}).trigger("reloadGrid");
            self.resizeGrid();
        },
        resizeGrid: function () {
            var self = this;
            var parentDom = $('#gbox_' + self.gridId.split('#')[1]).parent();
            $(self.gridId).setGridWidth(parentDom.width());
        }
    };

    

    // EVENT
    //=====================================================
    $("#searchBtnId").click(function(){
    	var searchTxt = $("#searchNameTxt").val();
    	gridObj.initGrid($("#brandId").val(), searchTxt);
    });
    
    $("#addBtnId").unbind().bind('click',function(){
    	window.location.href = 
        	webRoot + '/sys/editView?brandId='+parseInt($("#brandId").val());
    });
    
	$("#delBtnId").unbind().bind('click',function(){
		var productIds = $(gridObj.gridId).jqGrid('getGridParam','selarrrow');
        if(productIds.length > 0){
            var ids = "";
            $.post(urls.deleteProductByIds, {'idsArr':productIds.join()},function(rs){
            	if(rs.type){
            		alert("删除成功");
            		console.log($("#brandId").val());
            		gridObj.initGrid($("#brandId").val());
            	}else{
            		alert("删除失败");
            	}
              });
        }else{
            alert("请选择需要删除的记录！");
        }
	});
	
	//用jquery
	function getTextByJquery() {
	    var str = "";
	    //遍历name为txt的所有input元素
	    $("input[name='txt']").each(function () {
	        str += $(this).val() + ",";
	    });
	    //去掉最后一个逗号(如果不需要去掉，就不用写)
	    if (str.length > 0) {
	        str = str.substr(0,str.length - 1);
	    }
	    return str;
	}
    
    //=====================================================
    
    $(function(){
    	gridObj.init($("#brandId").val());
    });
});
